package com.app.backend.common.aware;

import com.app.backend.common.enums.EnvEnum;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author Jet Zheng
 * @Description: 项目初始化配置
 */
@Component
public class SpringContextAware implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static String profile;
    private static Boolean debugMode = null;


    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static boolean isTestEnv() {
        if (profile == null) {
            profile = applicationContext.getEnvironment().getActiveProfiles()[0];
        }
        return profile.contains(EnvEnum.DEV.getValue()) || profile.contains(EnvEnum.TEST.getValue());
    }

    public static boolean isLocalEnv() {
        if (profile == null) {
            profile = applicationContext.getEnvironment().getActiveProfiles()[0];
        }
        return profile.contains(EnvEnum.TEST.getValue());
    }

    public static boolean isDebugMode() {
        if (debugMode == null) {
            String property = Optional.ofNullable(applicationContext.getEnvironment().getProperty("profit.debug_mode")).orElse("false");
            debugMode = Boolean.parseBoolean(property);
        }
        return debugMode;
    }

    /**
     * 根据名称获取bean实例
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据类型获取bean实例
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

}
